C++ 如何建立 "数组数据成员 "的构造函数

来源:百度知道 编辑:UC知道 时间:2024/06/14 17:32:05
#include <iostream>
#include <string>
using namespace std;

class student
{public:
student()
{...... 这里如何初始化}
void display();
void set();
private:
int num;
int bar[6];
};

关键是数组要怎么写在构造函数里

方式一:用传递参数进行初始化。

#include <iostream>
#include <string>
using namespace std;

class student
{
public:
student(int n,int b[])
{
for (int i=0; i<6; i++)
{
bar[i] = b[i];
}
num = n;
}
void display();
void set();
private:
int num;
int bar[6];
};

void main()
{
int n=10,b[6]={1,2,3,4,5,6};
student stu(n,b); //用参数初始化
}

方式二、不传递参数进行初始化,和平时一般的程序对数组初始化没什么不一样的。

#include <iostream>
#include <string>
using namespace std;

class student
{
public:
student()
{
for (int i=0; i<6; i++)
{
bar[i] = 0;
}
num = 0;
}
void display();
void set();
private:
int num;
int bar[6];
};

void main()
{
student stu; //不带参数初始化
}

用循环
for(int i=0;i<6;i